<?php

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class KuaiShou
{
    static function session($code)
    {
        $config=config('kuaishou');
        $client=new Client();
        $resp=$client->post("https://open.kuaishou.com/oauth2/mp/code2session",[
            'form_params'=>[
                'js_code'=>$code,
                'app_id'=>$config['appid'],
                'app_secret'=>$config['secret']
            ]
        ]);
        if($resp->getStatusCode()===200){
            $ret=json_decode($resp->getBody()->getContents(),true);
            $code=Arr::get($ret,'result',0);
            if($code!=1){
                abort(500,'登录失败');
            }
            return [
                'key'=>Arr::get($ret,'session_key',''),
                'openid'=>Arr::get($ret,'open_id',0)
            ];
        }
        abort(500,'请求登录接口失败');
    }

    static function token(){
        $key="kf:kuaishou:token";
        $ret=Cache::get($key);
        if($ret){
            return $ret;
        }
        $config=config('kuaishou');
        $client=new Client();
        $url="https://open.kuaishou.com/oauth2/access_token?app_id={$config['appid']}&app_secret={$config['secret']}&grant_type=client_credentials";

        $resp=$client->get($url);
        if($resp->getStatusCode()===200){
            $data=json_decode($resp->getBody()->getContents(),true);
            if($data){
                $result=$data['result']??0;
                if($result){
                    $token=$data['access_token']??'';
                    $expires=$data['expires_in']??0;
                    if($token && $expires){
//                        $token='bearer '.$token;
                        Cache::put($key,$token,$expires-300);
                        return $token;
                    }
                }
            }
        }
        abort(500,'获取token失败');
    }

    static function pay($outNo,$openId,$amount,$subject,$detail){
        $token=self::token();
        $config=config('kuaishou');
        $url="https://open.kuaishou.com/openapi/mp/developer/epay/create_order?app_id={$config['appid']}&access_token={$token}";
        $client=new Client();
        $param=[
            'out_order_no'=>$outNo,
            'open_id'=>$openId,
            'total_amount'=>intval($amount*100),
            'subject'=>$subject,
            'detail'=>$detail,
            'type'=>3308,
            'expire_time'=>3600,
//            'goods_id'=>md5(time()),
            'notify_url'=>url('/notify/ks'),
        ];
        $param['sign']=self::sign($param);
        $resp=$client->post($url,[
            'json'=>$param
        ]);
        if($resp->getStatusCode()==200){
            return json_decode($resp->getBody()->getContents(),true);
        }
        abort(500,'请求支付发生错误');
    }

    static function sign($param)
    {
        $config=config('kuaishou');
        $param['app_id']=$config['appid'];
        ksort($param);
        $signstr='';
        foreach ($param as $k=>$v){
            if($v){
                $signstr.="{$k}={$v}&";
            }
        }
        $signstr=trim($signstr,'&').$config['secret'];
        Log::info($signstr);
        return md5($signstr);
    }
}
